/*
 * Background Flickr: Copyright (C) 2009  Craig McNicholas
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package com.ddw.app.bflickr.flickr.api.utils;

import java.io.StringReader;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;

import com.ddw.app.bflickr.logging.Log;
import com.ddw.app.bflickr.logging.LogFactory;

/**
 * Utilities class for handling xml
 * @author craig
 *
 */
public abstract class XmlUtils {
	
	private static Log log = LogFactory.createInstance(XmlUtils.class);

	/**
	 * Method to create the xml pull parser. Because we already have a response 
	 * a string reader is used to buffer the string into the pull parser instead 
	 * of from a file stream or otherwise.
	 * @param xml the xml string to parse
	 * @return the xml pull parser instance
	 * @throws XmlPullParserException if the pull parser encouters an error reading 
	 * from the response
	 */
	public static XmlPullParser createXmlParser(String xml) throws XmlPullParserException {
		XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
		factory.setNamespaceAware(false); // No namespacing for flickr
		XmlPullParser parser = factory.newPullParser();
		parser.setInput(new StringReader(xml));
		return parser;
	}
	
	/**
	 * Method to parse a string value to an integer also specifying a default value 
	 * if the conversion fails.
	 * @param value the string to parse to an integer
	 * @param defaultValue the default value to return if parsing fails
	 * @return the value of the string as an integer or the default value if the method fails
	 */
	public static int parseInt(String value, int defaultValue) {
		try {
			return Integer.parseInt(value);
		} catch(NumberFormatException ex) {
			log.error("The string value could not be converted to an integer", ex);
			return defaultValue;
		}
	}
	
}
